from django.shortcuts import render

# Create your views here.
from rest_framework import mixins
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet

from users.models import User

# 判断用户名是否存在
from users.serializers import RegisterCreateSerializer, UserDetailSerializer, EmailSerializer, AddressSerializer, \
    AddressTitleSerializer

# 验证链接
"""
请求方式：GET /users/emails/verification/
请求参数：
token  用于验证邮箱的token
返回数据： json
message 验证处理结果

"""


class VerificationEmailView(APIView):
    """
    验证激活邮箱
    GET /users/emails/verification/?token=xxxx

    思路:
    获取token,并判断
    获取 token中的id
    查询用户,并判断是否存在
    修改状态
    返回响应
    """
    def get(self,request):

        # 获取token,并判断
        token = request.query_params.get('token')
        if not token:
            return Response(
                {'message':'缺少token'},
                status=status.HTTP_400_BAD_REQUEST
            )

        # 获取 token中的id
        user = User.check_verify_email_token(token )

        # 查询用户,并判断是否存在
        if user is None:
            return  Response(
                {'message':'链接无效'},
                status=status.HTTP_400_BAD_REQUEST
            )
        else:

            # 修改状态
            user.email_active = True
            user.save()
            # 返回响应
            return Response({'message':'OK'})


# 保存邮箱并发送验证邮件
class EmailView(UpdateAPIView):
    """

    保存邮箱
    PUT /users/emails/

    """
    permission_classes = [IsAuthenticated]
    serializer_class =  EmailSerializer
    def get_object(self):
        return  self.request.user


# 用户详细信息视图  访问视图必须要求用户已通过认证（即登录之后）
class UserDetailView(RetrieveAPIView):
    """
    获取登录用户的信息
    GET /users/
    既然是登录用户,我们就要用到权限管理
    在类视图对象中也保存了请求对象request
    request对象的user属性是通过认证检验之后的请求用户对象
    """
    # 权限管理
    permission_classes = [IsAuthenticated]
    serializer_class = UserDetailSerializer

    def get_object(self):
        return self.request.user


# 用户注册状态
class RegisterUsernameCountAPIView(APIView):
    def get(self,request,username):
        count = User.objects.filter(username=username).count()
        context={
            'count':count,
            'username':username
        }
        return  Response(context)


# 判断手机号是否存在
class RegisterPhoneCountAPIView(APIView):
    def get(self,request,mobile):
        count = User.objects.filter(mobile=mobile).count()
        context={
            'count':count,
            'phone':mobile

        }
        return  Response(context)


class RegisterCreateView(CreateAPIView):
    """
        用户注册
        POST /users/

        用户注册我们需要对数据进行校验,同时需要数据入库
    """
    serializer_class = RegisterCreateSerializer


# 新增地址
class AddressViewSet(mixins.ListModelMixin,mixins.CreateModelMixin,mixins.UpdateModelMixin,mixins.DestroyModelMixin,GenericViewSet):

    serializer_class =  AddressSerializer
    # 添加用户权限
    permission_classes = [IsAuthenticated]
    # 由于用户的地址有存在删除的状态,所以我们需要对数据进行筛选
    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted = False)

    def create(self, request, *args, **kwargs):
        """
        保存用户地址数据
        """
        count = request.user.addresses.count()
        if count >=20:
            return Response(
                {'message':'保存地址数量已达到上线'},
                status= status.HTTP_400_BAD_REQUEST

            )
        return super().create(request,*args,**kwargs)

    def list(self, request, *args, **kwargs):
        """
        获取用户地址列表
        """
        # 获取所有地址
        queryset = self.get_queryset()
        # 创建序列化器
        serializer = self.get_serializer(queryset,many = True)
        user = self.request.user
        #相应
        return Response(
            {
                'user_id':user.id,
                'default_address_id':user.default_address_id,
                'limit':20,
                'addresses':serializer.data
             }
        )


    # 删除地址
    def destroy(self, request, *args, **kwargs):
        """
         处理删除
        """
        address = self.get_object()

        # 进行逻辑删除
        address.is_deleted = True
        address.save()
        return  Response(status=status.HTTP_204_NO_CONTENT)

    # 修改信息
    @action(methods =['put'] ,detail=True)
    def title(self,request,pk = None,address_id = None):
        """
        修改标题
        """
        address = self.get_object()
        serializer = AddressTitleSerializer(initial=address,data=request.data )
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return  Response(serializer.data)

    # 默认地址
    @action(methods = ['put'],detail=True)
    def status(self,request,pk=None,address_id = None):
        """

        设置默认地址
        """
        address = self.get_object()
        request.user.default_address = address
        request.user.save()
        return  Response(
            {'message':'ok'},
            status=status.HTTP_200_OK
        )

